package com.molihub.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.molihub.entity.*;
import com.molihub.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ArticleController
 * @Description: 文章管理器
 * @author: GGBOY
 * @date 2020/1/29 16:18
 * @Version: 1.0
 **/
@Controller
public class ArticleController extends BaseController {

    private Logger logger = LogUtils.getInstance(ArticleController.class);

    /**
     * @Description 获取用户所有标签
     * @Author xw
     * @Date 23:19 2020/1/31
     * @Param []
     * @return java.lang.String[]
     **/
    @ResponseBody
    @GetMapping("/getTags")
    public String[] getTags() {
        List<ArticleTag> tags = articleTagService.getArticleTagsByUserId(loginUser.getUserId());
        Integer size = tags.size();
        String[] result = new String[size];
        for (int i = 0; i < size; i++) {
            result[i] = tags.get(i).getArticleTagName();
        }
        System.out.println("请求标签");
        return result;
    }

    /**
     * @Description 发表文章
     * @Author xw
     * @Date 23:18 2020/1/31
     * @Param [article, inputTags]
     * @return java.lang.String
     **/
    @PostMapping("/publishArticle")
    public String publishArticle(Article article) {
        //公开发表
        article.setSecret(false);
        article.setArticleStatus(0);
        if (article.getArticleId() != null) {
            //如果文章ID不为空，那么说明当前强求来自重新编辑页面
            articleService.updateArticle(article);
            logger.info("编辑文章成功！信息：" + article);
            return "redirect:/all-published-articles";
        }else {
            //如果文章ID为空，那么说明当前强求来自发表新文章页面
            article.setUserId(loginUser.getUserId());
            article.setPublishTime(new Date());
            articleService.publishArticle(article);
            logger.info("发表文章成功！信息：" + article);
            return "redirect:/all-published-articles";
        }
    }

    /**
     * @Description 私密发表文章
     * @Author xw
     * @Date 23:18 2020/1/31
     * @Param [article, inputTags]
     * @return java.lang.String
     **/
    @PostMapping("/privatePublish")
    public String privatePublish(Article article) {
        //私密发表
        article.setSecret(true);
        article.setArticleStatus(0);
        if (article.getArticleId() != null) {
            //如果ArticleID不为空，那么说明当前强求来自重新编辑页面
            articleService.updateArticle(article);
            logger.info("编辑文章成功！信息：" + article);
            return "redirect:/all-published-articles";
        }else {
            //如果文章ID为空，那么说明当前强求来自发表新文章页面
            article.setUserId(loginUser.getUserId());
            article.setPublishTime(new Date());
            articleService.publishArticle(article);
            logger.info("发表私密文章成功！信息：" + article);
            return "redirect:/all-published-articles";
        }
    }

    /**
     * @Description 存入草稿
     * @Author xw
     * @Date 23:18 2020/1/31
     * @Param [article, inputTags]
     * @return java.lang.String
     **/
    @PostMapping("/savePublish")
    public String savePublish(Article article) {
        //存稿
        article.setSecret(false);
        article.setArticleStatus(1);
        if (article.getArticleId() != null) {
            //如果ArticleID不为空，那么说明当前强求来自重新编辑页面
            articleService.updateArticle(article);
            logger.info("编辑文章成功！信息：" + article);
            return "redirect:/all-draft-articles?current=1";
        }else{
            //如果文章ID为空，那么说明当前强求来自发表新文章页面
            article.setUserId(loginUser.getUserId());
            article.setPublishTime(new Date());
            articleService.publishArticle(article);
            logger.info("存入草稿成功！信息：" + article);
            return "redirect:/all-draft-articles?current=1";
        }
    }

    /**
     * @Description 获取所有的类别
     * @Author xw
     * @Date 23:53 2020/1/31
     * @Param []
     * @return java.util.List<com.molihub.entity.ArticleKind>
     **/
    @GetMapping("/getKinds")
    public List<ArticleKind> getKinds() {
        return articleKindService.getArticleKindsByUserId(loginUser.getUserId());
    }

    /**
     * 上传本地图片
     * @param file
     * @return
     */
    @RequestMapping("/markdown/upload")
    @ResponseBody
    public ResponseResult testUploadMarkDown(@RequestParam("editormd-image-file")MultipartFile file){
        ResponseResult responseResult = new ResponseResult();
        String filename = file.getOriginalFilename();
        try {
            if(file != null){
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream outputStream = new FileOutputStream(newFile);
                    outputStream.write(file.getBytes());
                    outputStream.close();
                    file.transferTo(newFile);
                    String url = aliyunOssUtil.upLoad(newFile);
                    responseResult.setSuccess(1);
                    responseResult.setUrl(url);
                    responseResult.setMessage("上传成功");
                    newFile.delete();
                }
            }
        } catch (FileNotFoundException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        } catch (IOException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        }
        return responseResult;
    }

    /**
     * @Description 将文章移入回收站
     * @Author xw
     * @Date 10:38 2020/2/3
     * @Param [articleId]
     * @return java.lang.String
     **/
    @GetMapping("/delete-article")
    public String deleteArticle(Integer articleId) {
        if (articleId != null) {
            if (articleService.updateArticle(Article.builder().articleId(articleId).articleStatus(2).build()) == 1) {
                logger.info("删除文章成功！id="+articleId);
            }else {
                logger.error("删除文章失败！id="+articleId);
            }
        }
        return "redirect:/all-published-articles";
    }

    @ResponseBody
    @PostMapping("/delete-post")
    public String deletePost(Integer articleId){
        if (articleId != null) {
            if (articleService.deleteArticle(articleId) == 1) {
                logger.info("删除文章成功！id="+articleId);
                return "OK";
            }else {
                logger.error("删除文章失败！id="+articleId);
                return "ERROR";
            }
        }
        return "ERROR";
    }

    @ResponseBody
    @PostMapping("/share")
    public String shareArticle(String userName, Integer articleId){
        // 要转发的文章
        Article toShareArticle = articleService.getArticleById(articleId);
        User user = userService.getUserByUserName(userName);
        toShareArticle.setUserId(user.getUserId());
        Integer row = articleService.publishArticle(toShareArticle);
        if(row == 1){
            return "OK";
        }else{
            return "ERROR";
        }
    }

    /**
     * @Description 彻底删除文章
     * @Author xw
     * @Date 10:38 2020/2/3
     * @Param [articleId]
     * @return java.lang.String
     **/
    @GetMapping("/completely-delete-article")
    public String completelyDeleteArticle(Integer articleId) {
        if (articleId != null) {
            if (articleService.deleteArticle(articleId) == 1) {
                logger.info("永久删除文章成功！id="+articleId);
            }else {
                logger.error("永久删除文章失败！id="+articleId);
            }
        }
        return "redirect:/all-trash-articles";
    }

    /**
     * @Description 重新发表文章
     * @Author xw
     * @Date 10:38 2020/2/3
     * @Param [articleId]
     * @return java.lang.String
     **/
    @GetMapping("/re-publish-article")
    public String rePublishArticle(Integer articleId) {
        if (articleId != null) {
            Integer result = articleService.updateArticle(
                    Article.builder().articleId(articleId).articleStatus(0).secret(false).build()
            );
            if (result == 1) {
                logger.info("发表文章成功！id="+articleId);
            }else{
                logger.error("发表文章失败！id="+articleId);
            }
        }
        return "redirect:/all-published-articles";
    }

    /**
     * @Description 重新发表私密文章
     * @Author xw
     * @Date 10:38 2020/2/3
     * @Param [articleId]
     * @return java.lang.String
     **/
    @GetMapping("/re-publish-private-article")
    public String rePublishPrivateArticle(Integer articleId) {
        if (articleId != null) {
            Integer result = articleService.updateArticle(
                    Article.builder().articleId(articleId).articleStatus(0).secret(true).build()
            );
            if (result == 1) {
                logger.info("重新发表私密文章成功！");
            }else{
                logger.error("重新发表私密文章成功！id="+articleId);
            }
        }
        return "redirect:/all-published-articles";
    }

    /**
     * @Description 搜索我的文章
     * @Author xw
     * @Date 13:32 2020/2/15
     * @Param [searchContent, current, map]
     * @return java.lang.String
     **/
    @GetMapping("search-my-articles")
    public String searchMyArticles(String searchContent, Integer current, Map<String, Object> map) {
        if ("".equals(searchContent.trim())) {
            return "redirect:/all-published-articles";
        }
        Integer pageSize = 10;
        //判断current参数是否为空，为空则默认当前页为1
        int cur = current == null? 1:current;
        //获得搜索结果总条数
        int total = articleService.getMyArticles(loginUser.getUserId(), searchContent).size();
        //获得文章数量的统计数据
        ArticleCountStatistics statistics = articleService.statistics(loginUser.getUserId());
        //搜索结果的总页数
        int maxPage = total % pageSize == 0 ? (total / pageSize) : (total / pageSize) + 1;
        //如果当前页大于最页，给当前页赋值为最大页。如果当前页小于等于0，那么赋值为第1页
        cur = cur >= maxPage ? maxPage : cur<=0 ? 1 :cur;
        Page<Object> page = PageHelper.startPage(cur, pageSize);
        List<Article> articles = articleService.getMyArticles(loginUser.getUserId(), searchContent);
        //将Article的集合转换为ArticleToShow的集合
        List<ArticleToShow> articleToShows = transformArticle(articles,loginUser);
        map.put("searchContent", searchContent);
        map.put("statistics", statistics);
        map.put("page", page);
        map.put("articles", articleToShows);
        return "u-admin/search-articles";
    }

    /**
     * @Description 添加标签或者分类目录
     * @return java.lang.String
     * @Author xw
     * @Date 13:34 2020/2/3
     * @Param [kindName, tagName]
     **/
    @PostMapping("/addArticleKindOrTag")
    public String addArticleKindOrTag(String kindName, String tagName) {
        if (kindName == null && tagName == null){
            return "redirect:/article-kinds-tags";
        }
        //分类目录不为空，增加分类目录
        if (kindName != null) {
            if ("".equals(kindName.trim())){
                return "redirect:/article-kinds-tags";
            }
            articleKindService.addArticleKind(
                    ArticleKind.builder().articleKindName(kindName).userId(loginUser.getUserId()).build());
        }
        //标签不为空，增加文章标签
        if (tagName != null) {
            if ("".equals(tagName.trim())){
                return "redirect:/article-kinds-tags";
            }
            articleTagService.addArticleTag(
                    ArticleTag.builder().articleTagName(tagName).userId(loginUser.getUserId()).build());
        }
        return "redirect:/article-kinds-tags";
    }

    /**
     * @Description 删除标签或分类目录
     * @Author xw
     * @Date 13:48 2020/2/3
     * @Param [tagId, kindId]
     * @return java.lang.String
     **/
    @GetMapping("/deleteArticleKindOrTag")
    public String deleteArticleKindOrTag(Integer tagId, Integer kindId) {
        //分类目录不为空，删除分类目录
        if (kindId != null) {
            ArticleKind kind = articleKindService.getArticleKindById(kindId);
            articleService.deleteArticleKind(loginUser.getUserId(), kind.getArticleKindName());
            articleKindService.deleteArticleKind(ArticleKind.builder().articleKindId(kindId).build());
        }
        //标签不为空，删除标签
        if (tagId != null) {
            ArticleTag tag = articleTagService.getArticleTagById(tagId);
            articleService.deleteArticleTag(loginUser.getUserId(), tag.getArticleTagName());
            articleTagService.deleteArticleTag(ArticleTag.builder().articleTagId(tagId).build());
        }
        return "redirect:/article-kinds-tags";
    }

    /**
     * @Description 修改标签或分类目录
     * @Author xw
     * @Date 13:49 2020/2/3
     * @Param [tagName, kindName]
     * @return java.lang.String
     **/
    @PostMapping("/editArticleKindOrTag")
    public String editArticleKindOrTag(String tagName, Integer tagId, String kindName, Integer kindId) {
        //分类目录不为空，编辑分类目录
        if (kindName != null) {
            ArticleKind kindById = articleKindService.getArticleKindById(kindId);
            articleService.updateArticleKind(loginUser.getUserId(), kindName, kindById.getArticleKindName());
            ArticleKind kind = ArticleKind.builder().articleKindId(kindId).build();
            kind.setArticleKindName(kindName);
            articleKindService.updateArticleKind(kind);
        }
        //标签不为空，编辑标签
        if (tagName != null) {
            ArticleTag tagById = articleTagService.getArticleTagById(tagId);
            articleService.updateArticleTag(loginUser.getUserId(), tagName, tagById.getArticleTagName());
            ArticleTag tag = ArticleTag.builder().articleTagId(tagId).build();
            tag.setArticleTagName(tagName);
            articleTagService.updateArticleTag(tag);
        }
        return "redirect:/article-kinds-tags";
    }

    /**
     * @Description 将Article集合转为ArticleToShow集合
     * @Author xw
     * @Date 15:38 2020/2/15
     * @Param [list, user]
     * @return java.util.List<com.molihub.entity.ArticleToShow>
     **/
    private List<ArticleToShow> transformArticle(List<Article> list,User user){
        List<ArticleToShow> result = new ArrayList<>();
        for (Article article : list) {
            ArticleToShow temp = ArticleToShow.builder()
                    .article(article).author(user)
                    .likeCount(articleService.getLikeCountByArticle(article.getArticleId()))
                    .commentCount(articleService.getCommentCountByArticle(article.getArticleId())).build();
            result.add(temp);
        }
        return result;
    }
}
